// utils/network-debug.js
// 网络诊断工具 - 排查微信小程序网络请求问题

class NetworkDebugger {
  constructor() {
    this.testUrls = [
      'https://www.baidu.com',
      'https://www.qq.com',
      'https://www.taobao.com',
      'https://iam.cn-north-4.myhuaweicloud.com',
      'https://ocr.cn-north-4.myhuaweicloud.com'
    ]
  }

  // 测试基本网络连接
  async testBasicNetwork() {
    console.log('=== 基本网络连接测试 ===')
    
    const results = []
    
    for (const url of this.testUrls) {
      try {
        console.log(`测试连接: ${url}`)
        
        const response = await wx.request({
          url: url,
          method: 'GET',
          timeout: 10000
        })
        
        console.log(`✅ ${url} 连接成功`)
        console.log(`  状态码: ${response.statusCode}`)
        console.log(`  状态: ${response.status}`)
        console.log(`  数据长度: ${response.data ? JSON.stringify(response.data).length : 0}`)
        console.log(`  响应头: ${response.header ? Object.keys(response.header).length : 0} 个`)
        
        results.push({
          url,
          success: true,
          statusCode: response.statusCode,
          status: response.status,
          hasData: !!response.data,
          hasHeader: !!response.header
        })
      } catch (error) {
        console.log(`❌ ${url} 连接失败: ${error.message}`)
        results.push({
          url,
          success: false,
          error: error.message
        })
      }
    }
    
    return results
  }

  // 测试华为云Token请求
  async testHuaweiTokenRequest() {
    console.log('=== 华为云Token请求测试 ===')
    
    const tokenUrl = 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens'
    
    const tokenRequest = {
      auth: {
        identity: {
          methods: ['password'],
          password: {
            user: {
              name: 'ilieyun',
              password: 'Lieyun@2090',
              domain: {
                name: 'ilieyun'
              }
            }
          }
        },
        scope: {
          project: {
            name: 'cn-north-4'
          }
        }
      }
    }

    try {
      console.log('发送Token请求...')
      console.log('URL:', tokenUrl)
      console.log('请求体:', JSON.stringify(tokenRequest, null, 2))

      // 使用Promise包装wx.request
      const response = await new Promise((resolve, reject) => {
        const requestTask = wx.request({
          url: tokenUrl,
          method: 'POST',
          data: tokenRequest,
          header: {
            'Content-Type': 'application/json'
          },
          timeout: 15000,
          success: (res) => {
            console.log('请求成功回调:', res)
            resolve(res)
          },
          fail: (err) => {
            console.log('请求失败回调:', err)
            reject(err)
          }
        })
        
        // 监听请求进度
        requestTask.onHeadersReceived((res) => {
          console.log('收到响应头:', res.header)
        })
        
        requestTask.onProgressUpdate((res) => {
          console.log('请求进度:', res)
        })
      })

      console.log('完整响应对象:', response)
      console.log('响应类型:', typeof response)
      console.log('响应键名:', Object.keys(response))
      
      return {
        success: true,
        response: response,
        statusCode: response.statusCode,
        status: response.status,
        hasData: !!response.data,
        hasHeader: !!response.header,
        headerKeys: response.header ? Object.keys(response.header) : []
      }
    } catch (error) {
      console.log('Token请求异常:', error)
      return {
        success: false,
        error: error.message,
        stack: error.stack
      }
    }
  }

  // 测试不同的请求配置
  async testRequestConfigurations() {
    console.log('=== 请求配置测试 ===')
    
    const testUrl = 'https://www.baidu.com'
    const configs = [
      { name: '默认配置', config: {} },
      { name: '增加超时', config: { timeout: 10000 } },
      { name: '增加头部', config: { header: { 'User-Agent': 'WeChat' } } },
      { name: '完整配置', config: { 
        timeout: 10000, 
        header: { 'User-Agent': 'WeChat' },
        enableHttp2: true,
        enableQuic: true
      }}
    ]
    
    const results = []
    
    for (const { name, config } of configs) {
      try {
        console.log(`测试配置: ${name}`)
        
        const response = await wx.request({
          url: testUrl,
          method: 'GET',
          ...config
        })
        
        console.log(`✅ ${name} 成功`)
        results.push({
          name,
          success: true,
          statusCode: response.statusCode,
          hasData: !!response.data,
          hasHeader: !!response.header
        })
      } catch (error) {
        console.log(`❌ ${name} 失败: ${error.message}`)
        results.push({
          name,
          success: false,
          error: error.message
        })
      }
    }
    
    return results
  }

  // 检查微信小程序配置
  checkWechatConfig() {
    console.log('=== 微信小程序配置检查 ===')
    
    const config = {
      // 检查是否在开发工具中
      isDevTools: wx.getSystemInfoSync().platform === 'devtools',
      
      // 检查网络类型
      networkType: wx.getNetworkType ? '需要异步获取' : '不可用',
      
      // 检查基础库版本
      SDKVersion: wx.getSystemInfoSync().SDKVersion,
      
      // 检查系统信息
      systemInfo: wx.getSystemInfoSync()
    }
    
    console.log('配置信息:', config)
    return config
  }

  // 运行完整诊断
  async runFullDiagnosis() {
    console.log('=== 网络完整诊断开始 ===')
    
    try {
      // 1. 检查微信小程序配置
      const config = this.checkWechatConfig()
      
      // 2. 测试基本网络连接
      const networkResults = await this.testBasicNetwork()
      
      // 3. 测试请求配置
      const configResults = await this.testRequestConfigurations()
      
      // 4. 测试华为云Token请求
      const tokenResults = await this.testHuaweiTokenRequest()
      
      // 5. 获取网络类型
      let networkType = '未知'
      try {
        const networkRes = await new Promise((resolve, reject) => {
          wx.getNetworkType({
            success: resolve,
            fail: reject
          })
        })
        networkType = networkRes.networkType
      } catch (error) {
        console.log('获取网络类型失败:', error)
      }
      
      const diagnosis = {
        config,
        networkType,
        networkResults,
        configResults,
        tokenResults
      }
      
      console.log('=== 诊断结果 ===')
      console.log('完整诊断结果:', diagnosis)
      
      return diagnosis
    } catch (error) {
      console.log('诊断过程异常:', error)
      throw error
    }
  }
}

module.exports = new NetworkDebugger()
